from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.response import Response
from dvadmin.utils.viewset import CustomModelViewSet
from .models import PurchasePlan, PurchaseDetail
from .serializers import (
    PurchasePlanSerializer, 
    PurchasePlanCreateUpdateSerializer,
    PurchaseDetailSerializer,
    PurchaseDetailCreateUpdateSerializer
)

# Create your views here.

class PurchasePlanModelViewSet(CustomModelViewSet):
    """
    采购计划管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = PurchasePlan.objects.all()
    serializer_class = PurchasePlanSerializer
    create_serializer_class = PurchasePlanCreateUpdateSerializer
    update_serializer_class = PurchasePlanCreateUpdateSerializer
    permission_classes = []  # 移除权限校验
    extra_filter_class = []  # 移除数据过滤器

    def get_queryset(self):
        queryset = super().get_queryset()
        # 如果请求中包含status参数，则按状态过滤
        status = self.request.query_params.get('status', None)
        if status is not None:
            queryset = queryset.filter(status=status)
        return queryset

    @action(detail=True, methods=['post'])
    def approve(self, request, *args, **kwargs):
        """审批采购计划"""
        instance = self.get_object()
        action = request.data.get('action')
        
        if action == 'approve':
            instance.status = 1
        elif action == 'reject':
            instance.status = 2
        else:
            return Response({'error': '无效的操作'}, status=400)
            
        instance.save()
        return Response({'status': 'success'})

class PurchaseDetailModelViewSet(CustomModelViewSet):
    """
    采购明细管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = PurchaseDetail.objects.all()
    serializer_class = PurchaseDetailSerializer
    create_serializer_class = PurchaseDetailCreateUpdateSerializer
    update_serializer_class = PurchaseDetailCreateUpdateSerializer
    permission_classes = []  # 移除权限校验
    extra_filter_class = []  # 移除数据过滤器
